#include "BallModel.h"
#include "Ball.h"
#include "GraphicManager.h"
#include "Params.h"
#include <math.h>
#include "Application.h"
#include <iostream>
#include "GameState.h"


using namespace std;

BallModel::BallModel(Ball* owner) : Model("Ball"),
									m_owner(owner),
									m_lastAngleCos(-1),
									m_side(1),
									m_lastAxis(1,0)
{
}

BallModel::~BallModel()
{
}

void BallModel::Draw(const sf::Vector2f& offset, const sf::Vector2f& facing)
{
	//m_frame+=m_period;
	//if(m_frame > m_maxFrame) m_frame = 0;
	float ray = 2.4f;

	glPushMatrix();

	//Identical(correct en?=P) Matrix
	GLfloat matrix[] = {
		1.f, 0.f, 0.f, 0.f, 
		0.f, 1.f, 0.f, 0.f, 
		0.f, 0.f, 1.f, 0.f, 
		0.f, ray, 0.f, 1.f};

	/*
	//rotation on Y
	matrix[0] = facing.y;
	matrix[10] = facing.y;		

	if (facing.x != 0.f)
	{
		matrix[2] = -facing.x;
		matrix[8] = facing.x;
	}
	*/
	//Traslation offset
	matrix[12] = offset.x;
	matrix[14] = offset.y;

	glMultMatrixf(matrix);

	/////////////////////////////////////////////////////////////////////////////
	
	float speed = m_owner->GetSpeed().Length();

	if (speed != 0.f && Application::Istance()->GetCurrentStateName()!="Pause")
	{
		float updFactor = Params::GameUpdateTime/(static_cast<GameState*>(Application::Istance()->GetCurrentState()))->GetUpdateTime();
		float rotSpeed = speed / 8.f * updFactor;

		m_lastAngleCos += m_side*rotSpeed;
		if (m_lastAngleCos*m_side >= 1)
		{
			float diff = m_lastAngleCos - m_side;
			m_lastAngleCos = m_side - diff;
			m_side *= -1;
		}
		m_lastAxis = Vector2(-m_owner->GetSpeed().y, m_owner->GetSpeed().x).NormalizeCopy();
	}

	float c = m_lastAngleCos;
	float s = -m_side*sqrt(1-(c*c));
	//std::cerr << "cos: " << c << "   sen: " << s << std::endl;
	
	float ux = m_lastAxis.x;
	float uy = 0;
	float uz = m_lastAxis.y;

	GLfloat rot[] = {
		(1.f - c)*ux*ux + c,		(1.f - c)*ux*uy - s*uz,		(1.f - c)*ux*uz + s*uy,		0.f,
		(1.f - c)*ux*uy + s*uz,		(1.f - c)*uy*uy + c,		(1.f - c)*uy*uz - s*ux,		0.f,
		(1.f - c)*ux*uz - s*uy,		(1.f - c)*uy*uz + s*ux,		(1.f - c)*uz*uz + c,		0.f,
		0.f,						0.f,						0.f,						1.f
	};

	glMultMatrixf(rot);
	

	
	GLfloat t[] = {1.f, 0.f, 0.f, 0.f, 
		0.f, 1.f, 0.f, 0.f, 
		0.f, 0.f, 1.f, 0.f, 
		0.f, -ray, 0.f, 1.f};
	glMultMatrixf(t);
	/////////////////////////////////////////////////////////////////////////////

	RenderMeshs();

	glPopMatrix();
}